package com.zdp.nio.reactor;

import com.zdp.nio.reactor.handle.EchoHandler;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Objects;

/**
 * 监听IO事件，将其分发给对应的 handle
 */
public class EchoReactor implements Runnable{

    private Selector selector;

    private ServerSocketChannel server;

    public EchoReactor(Integer port) throws IOException {
        selector = Selector.open();
        server = ServerSocketChannel.open();
        server.configureBlocking(false);
        server.bind(new InetSocketAddress(port));
        SelectionKey register = server.register(selector, SelectionKey.OP_ACCEPT);
        register.attach(new AcceptHandler());
    }

    @Override
    public void run() {
        try{
            while(!Thread.interrupted()) {
                // 阻塞监听
                selector.select();
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while(iterator.hasNext()){
                    SelectionKey next = iterator.next();
                    dispatch(next);
                    iterator.remove();
                }

            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    private void dispatch(SelectionKey key){
        Runnable handle = (Runnable) key.attachment();
        if(Objects.nonNull(handle)){
            // 这个run ...
            handle.run();
        }
    }

    class AcceptHandler implements Runnable {
        @Override
        public void run() {
            try{
                SocketChannel channel = server.accept();
                if(channel != null){
                    // 在该构造方法中，进行Socket的绑定操作
                    new EchoHandler(selector,channel);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void main(String[] args) throws IOException {
            new Thread(new EchoReactor(9905)).start();
    }
}
